#Create wordlist based on minimum word length input
#Shad Malloy shad.malloy@knowledgecg.com
#
#4/18/2013
#
#!/usr/bin/python
import sys
import os
import getopt
from os import path, access, remove

def main(argv):
   inputFilePath = ''
   outputFilePath = ''
   inputMinLen = ''
   try:
      opts, args = getopt.getopt(sys.argv[1:],"hi:o:l:",["inputFilePath=","outputFilePath=","inputMinLen="])
   except getopt.GetoptError:
      print 'Usage is dictbylenth.py -i <inputfile> -o <outputfile> -l <minimumlength>'

   for opt,arg in opts:
      if opt == '-h':
         print 'dictbylenth.py -i <inputfile> -o <outputfile> -l <minimumlength>'
         sys.exit()
      elif opt in ("-i"):
         inputFilePath = arg
      elif opt in ("-o"):
         outputFilePath = arg
      elif opt in ("-l"):
         inputMinLen = arg
      else:
         assert False, "Option not recognized: try -h for usage"


   #Open original wordlist
   if path.exists(inputFilePath) and path.isfile(inputFilePath):
      print 'Input file found'
   else:
      print 'Input file either isn\'t a file or doesn\'t exist. Exiting'

      

   #Open file for read
   try:
       inputWordList = open(inputFilePath, 'rb').readlines()
   except:
       return
        

   #Open output for write
   if path.exists(outputFilePath):
      print 'Checking output file ' + outputFilePath + ' removing if exists'
      remove(outputFilePath)

   #Open output file for write
   try:   
      outputFile = open(outputFilePath, 'w')
   except:
      print 'Error opening file for write.'
      sys.exit()

   #Read in line and check length, write to file if greater than or equal to inputMinLen
   outCount = 0
   print 'Writing all words longer than ' + inputMinLen + ' to file'
   for line in inputWordList:
      line = line.rstrip()
      if len(line.rstrip()) >= int(inputMinLen):
         outString = line+'\n'
         outputFile.write(outString)
         outCount += 1

   #Clean up
   print (str(outCount)) + ' written to file  at ' + outputFilePath
   outputFile.close()

if __name__ =="__main__":
   main(sys.argv[1:])

